package com.sharekitchen.controller;

import com.sharekitchen.common.R;
import com.sharekitchen.entity.Order;
import com.sharekitchen.entity.PieChart;
import com.sharekitchen.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/order")
public class OderController {

    @Autowired
    private OrderService orderService;

    //    查询所有订单信息
    @GetMapping("/all")
    public R<List<Order>> findAllOrder() {
        List<Order> allOrder = orderService.findAllOrder();
        if (allOrder != null) {
            return R.ok("查询成功", allOrder);
        }
        return R.error("查询失败");
    }

    //    查询所有订单信息
    @GetMapping("/id")
    public R<Order> findOrderById(@RequestParam String orderId) {

        Order order = orderService.findOrderById(orderId);

        if (order != null) {
            return R.ok("查询成功", order);
        }

        return R.error("订单不存在");
    }

    @PostMapping("/add")
    public R<String> addOrder(@RequestBody Order order) {
        order.setOrderId(UUID.randomUUID().toString().replace("-", "").substring(0, 20));
        if (orderService.addOrder(order)) {
            return R.ok("添加成功", null);
        }
        return R.fail("添加失败");
    }


    @DeleteMapping("/delete")
    public R<String> deleteOrderById(@RequestParam String orderId) {
        if (orderService.deleteOrderById(orderId)) {
            return R.ok("删除成功", null);
        }
        return R.error("删除失败");
    }

    @PutMapping("/change")
    public R<String> updateOrder(@RequestBody Order order) {
        Order oldOrder = orderService.findOrderById(order.getOrderId());
        if (oldOrder == null) {
            return R.fail("该订单不存在");
        }
        if (orderService.updateOrder(order)) {
            return R.ok("修改成功", null);
        }
        return R.fail("修改失败");
    }

    @GetMapping("/pie")
    public R<List<PieChart>> getPieChart(){
        List<PieChart> pieChartData = orderService.getPieChartData();
        if (pieChartData != null){
            return R.ok("查询成功",pieChartData);
        }
        return R.fail("查询失败");
    }

}
